const _getHttp = Symbol('_getHttp'),
    _sendServerMsg = Symbol('_sendServerMsg');
export default class Controller {
    static fnArr = [
        { fnName: 'sendTalkMsg', params: ['talk_id', 'content', 'type'], tip: '发送会话消息' },
        { fnName: 'makeDialogue', params: ['title', 'toMemberId', 'content'], tip: '创建临时会话' },
        { fnName: 'editSelfName', params: ['name'], tip: '修改用户姓名' },
        { fnName: 'editAvatarurl', params: ['file'], tip: '修改用户头像' },
        { fnName: 'addFriendUseMemberId', params: ['member_id'], tip: '通过MemberId添加好友 ' },
        { fnName: 'addFriendUseTalkId', params: ['talk_id'], tip: '通过TalkId添加好友' },
        { fnName: 'examineToFriend', params: ['clientMsgId', 'userSelect'], tip: '审核好友' },
        { fnName: 'deleteFriend', params: ['talk_id'], tip: '删除好友' },
        { fnName: 'findFriendFromTel', params: ['tel'], tip: '通过手机号搜索用户' },
        { fnName: 'fetchFriendApplyList', params: [] },
        { fnName: 'addTalkObjectCallback', params: ['onNewChatAlert', 'onListRefresh', 'onTalkDetailRefresh', 'onTalkWithMsg'], tip: 'talkObject 添加回调函数。' },
        { fnName: 'getTalkList', params: [], tip: "获取会话列表" },
        { fnName: 'getChat', params: ['talk_id'], tip: "获取历史记录" },
        { fnName: 'fetchFriendApplyList', params: [], tip: "获取申请列表数据" },
        { fnName: 'resend', params: [], tip: "消息重发" },
        { fnName: 'getTalkDetail', params: ['talk_id'], tip: "取会话用户信息" },
        { fnName: 'exitTalk', params: [], tip: "用户退出聊天界面" },
    ]
    constructor(socket) {
        this.socket = socket;
    }
    setProperty(member_id, token, key, h_url, a_url, e_url) {
        /* member_id,token,key,a_url,h_url,e_url*/
        console.log(member_id, token, key);
        this.member_id = member_id;
        this.token = token;
        this.key = key;
        this.h_url = h_url;
        this.a_url = a_url;
        this.e_url = e_url;
    }
    action(fnName, params, callback, failCallback) {
        const fn = Controller.fnArr.find(item => { if (item.fnName == fnName) { return item } })
        // 验证方法名
        if (!fn) { alert(fnName + '方法不存在！'); return { code: 301, data: fnName + '方法不存在！' } }
        const paramsList = [];
        //验证参数 ,noMust属性判断参数是否可以为空值。
        const loseKey = fn.params.find((item) => { if (!params[item] && !params.noMust) { return item } paramsList.push(params[item]) })
        if (loseKey) {
            alert(fnName + '函数缺少' + loseKey + '参数!');
            const data = { code: 301, data: fnName + '函数缺少' + loseKey + '参数!' };
            failCallback && failCallback(data);
            return
        }
        return this[fnName](...paramsList, callback, failCallback);
    }
    /*发送会话消息*/
    sendTalkMsg(talk_id, content, type, callback, failCallback) {
        if (!talk_id || !content || !type) { console.log("发送会话消息 缺少参数！"); return }
        const ret = this.socket.sendController.pushMessage("talk", { content: content, talk_id: Number(talk_id), type: type }, this.member_id, callback, failCallback);
        if (ret.code != 200) { return ret.data }
        console.log(ret);
        this.socket.sendController.sendMessage(ret.data.data.head.clientMsgId);
        // this[_sendServerMsg]('talk', { content: content, talk_id: talk_id, type: type }, this.member_id, callback, failCallback);
    }
    /*创建临时会话*/
    makeDialogue(title, toMemberId, content, succCallback, failCallback) {
        if (!title || !toMemberId) {
            confirm("参数缺失！");
            return { code: 301, data: "参数缺失！" }
        }
        if (toMemberId == this.member_id) {
            alert("toMemberId 和 用户MemberId 相同！");
            return { code: 301, data: "toMemberId 和 用户MemberId 相同！" }
        }
        if (typeof content != 'object') {
            alert('content 必须为 对象类型！');
            return { code: 301, data: 'content 必须为 对象类型！' }
        }
        content = JSON.parse(JSON.stringify(content))
        var token = this.token;
        this[_getHttp](this.h_url + "/makeTemporaryTalk", { title, token, toMemberId },
            data => {
                if (data.code == 200) {
                    const msg = this.socket.sendController.pushMessage("makeTemporaryTalk", { dialogueKey: data.data.dialogueKey }, toMemberId, (data) => {
                        succCallback && succCallback(data);
                        this.sendTalkMsg(data.body.data.talk.id, content, 2)
                    }, failCallback);
                    this.socket.sendController.sendMessage(msg.data.data.head.clientMsgId);
                } else {
                    alert("请求错误！" + data.data);
                    return { code: 301, data: data.data }
                }
            }
        );
    }
    /*更改用户头像*/
    editAvatarurl(file, callback) {
        let url = this.a_url + '/editAvatarurl?key=' + this.key;
        const formdata = new FormData();
        formdata.append('file', file);
        return new Promise((resolve, reject) => {
            var xmlpost = new XMLHttpRequest();
            xmlpost.open("post", url, true);
            xmlpost.send(formdata);
            xmlpost.onreadystatechange = () => {
                if (xmlpost.readyState == 4) {
                    if (xmlpost.status == 200) {
                        this[_sendServerMsg]('refreshInEditSelfInfo', {}, this.member_id);
                        const data = JSON.parse(xmlpost.responseText);
                        callback(data);
                        // console.log(123);
                        resolve(data);
                        const index = data.data.avatarurl.indexOf('/public');
                        var str = data.data.avatarurl.substr(index, data.data.avatarurl.length);
                        this.socket.talkObject.talkList.forEach(item => {
                            item.talkPartakeMembers.find(person => {
                                if (person.member_id == this.member_id) {
                                    person.avatarurl = str;
                                    this.socket.talkObject.initLocalStorage();
                                    return
                                }
                            })
                        })
                    } else {
                        reject(JSON.parse(xmlpost.responseText));
                    }
                }
            }
        })

    }
    /*更改用户姓名*/
    editSelfName(name, callback) {
        if (!name) { alert("用户名为空!"); return }
        let url = this.a_url + '/editSelfName';
        return new Promise((resolve, reject) => {
            this[_getHttp](url, { name, key: this.key }, (data) => {
                callback(data);
                if (data.code != 200) { reject(data); console.log(data.data); return }
                this[_sendServerMsg]('refreshInEditSelfInfo', {}, this.member_id);              //修改成功时，发送一条消息确认
                resolve(data);
                this.socket.talkObject.talkList.forEach(item => {
                    item.talkPartakeMembers.find(person => {
                        if (person.member_id == this.member_id) {
                            person.name = name;
                            this.socket.talkObject.initLocalStorage()
                            return
                        }
                    })

                })
            })
        })
    }
    [_getHttp](url, params, callback) {
        for (let i in arguments) {
            if (arguments[i] == undefined || arguments[i] == '') {
                alert("getHttp参数，第 " + i + "个参数不能为空！");
                return
            }
        }
        var xmlpost = new XMLHttpRequest();
        xmlpost.open("post", url, true);
        var postData = [];
        if (params) {
            for (let i in params) {
                postData.push(i + "=" + params[i]);
            }
            postData = postData.join("&");
        }
        xmlpost.send(postData);
        xmlpost.onreadystatechange = function () {
            if (xmlpost.readyState == 4) {
                if (xmlpost.status == 200) {
                    var data = JSON.parse(xmlpost.responseText);
                    callback(data);
                    if (data.code != 200) {
                        console.log("请求出错", data.data);
                    }
                }
            }
        };
    }
    /*发送服务器信息*/
    [_sendServerMsg](sign, content, toMemberId, succCallback, failCallback) {
        for (let i in arguments) {
            if (arguments[i] == '' || arguments[i] == undefined || arguments[i] == null) {
                alert("sendServerMsg，第" + i + "个参数不能为空！");
                return { code: 301, data: 'sendServerMsg，第' + i + '个参数不能为空！！' }
            }
        }
        const msg = this.socket.sendController.pushMessage(sign, content, toMemberId, succCallback, failCallback);
        if (msg.code != 200) {
            alert("消息创建失败！");
            return { code: 301, data: '消息创建失败！' }
        }
        this.socket.sendController.sendMessage(msg.data.data.head.clientMsgId);
    }
    /*跟据用户id添加好友*/
    addFriendUseMemberId(member_id, callback) {
        this[_sendServerMsg]('addFriendUseMemberId', { member_id: Number(member_id) }, this.member_id, (data) => {
            callback && callback(data);
        });  //修改成功时，发送一条消息确认
    }
    /*跟据临时会话id添加好友*/
    addFriendUseTalkId(talk_id, callback) {
        this[_sendServerMsg]('addFriendUseTalkId', { talk_id: Number(talk_id) }, this.member_id, (data) => {
            callback && callback(data)
        });      //修改成功时，发送一条消息确认
    }
    /*审核添加好友*/
    examineToFriend(clientMsgId, userSelect, callback) {
        //找到好友请求  
        const res = this.socket.friendObject.resolveAgree(clientMsgId);
        if (res.code != 200) { alert(res.data); return }
        // 'fromType'=> '1临时会话，2手机号，3群聊',
        // 'fromTitle'=> 'xxx'
        //验证参数
        if (userSelect != 1 && userSelect != -1) { return { code: 301, data: 'userSelect 格式错误！' } }
        //用户拒绝添加好友时，不操作
        let fn = () => { };
        if (userSelect == 1) {
            //添加好友成功时，改变会话列表类型
            fn = data => {
                if (data.body.code == 200) {
                    this.socket.friendObject.addFriend(data.body.data.talk_id);
                    this.socket.talkObject.changeTalkType(data.body.data.talk_id, 2)
                } else {
                    console.log("添加好友失败！", data);
                }
            }
        }
        this[_sendServerMsg]('examineToFriend', {
            oliveBranchKey: res.data.body.oliveBranchKey,
            type: userSelect
        }, this.member_id, (data) => {
            fn(data);
            callback && callback(data);
        });

    }
    /*删除好友*/
    deleteFriend(talk_id, callback) {
        // 删除好友成功时，执行回调
        this[_sendServerMsg]('delFriend', { talk_id }, this.member_id, (data) => {
            callback && callback(data);
            if (data.body.code == 200) {
                this.socket.talkObject.deleteTalk(talk_id);
                this.socket.friendObject.deleteFriend(talk_id);
            } else {
                console.log("删除好友失败!", data);
            }
        })
    }
    /*通过手机号搜索用户*/
    findFriendFromTel(tel, callback) {
        if (!tel) { tel = prompt("输入手机号.") }
        this[_sendServerMsg]('findFriendFromTel', { tel }, this.member_id, callback);
        //修改成功时，发送一条消息确认
    }
    fetchFriendApplyList() {
        var data = this.socket.friendObject.getAppList();
        return data;
    }
    exitTalk() {
        this.socket.talkObject.exitTalk();
    }
    /*talkObject添加回调函数*/
    addTalkObjectCallback(onNewChatAlert, onListRefresh, onTalkDetailRefresh, onTalkWithMsg) {
        // for (let i of arguments) {
        //     if (typeof i != "function") {
        //         confirm("参数必须为函数！")
        //         return
        //     }
        // }
        this.socket.talkObject.addCallBack(onNewChatAlert, onListRefresh, onTalkDetailRefresh, onTalkWithMsg)
    }
    /*取会话列表*/
    getTalkList() {
        return this.socket.talkObject.getTalkList();
    }
    getChat(talk_id) {
        if (!talk_id) {
            talk_id = prompt("请输入talk_id")
        }
        return this.socket.talkObject.getChat(talk_id);
    }
}